import { Alert, Linking } from 'react-native'
import Permissions from 'react-native-permissions'
import { IS_ANDROID } from './ScreenUtil'
import { CommonToast } from './ToastUtil'
// https://github.com/yonahforst/react-native-permissions
/*
 type: 'location',
 showAlert: true,
 alertConfig: {
   title: '人职初需要访问您的位置',
   btnTexts: ['取消', '去开启']
  }
*/
export function CustomPermissions ({ type, showAlert = false, alertConfig }) {
  if (!type) {
    throw new Error('需要一个权限类型')
  }
  return new Promise((resolve, reject) => {
    Permissions.request(type).then(response => {
      console.log('CustomPermissions', type, response)
      if (response === 'authorized') {
        resolve(response)
      } else {
        if (showAlert && alertConfig) {
          CustomAlert(alertConfig).then(() => {
            Permissions.canOpenSettings().then(can => {
              if (can) {
                Permissions.openSettings()
              }
            })
          })
        }
        reject(response)
      }
    }).catch((data) => {
      console.info(data)
    })
  })
}

export function CustomAlert ({
  title = '提示',
  subtitle = '',
  btnTexts,
  cancelIndex = 0,
  cancelable = false
}) {
  return new Promise((resolve, reject) => {
    Alert.alert(
      title,
      subtitle,
      btnTexts.map((text, index) => ({
        text,
        style: cancelIndex === index ? 'cancel' : '',
        onPress: () => (cancelIndex === index ? reject(index) : resolve(index))
      })),
      { cancelable }
    )
  })
}

export function CustomCallPhone (phone) {
  new Promise((resolve) => {
    if (IS_ANDROID) {
      CustomPermissions({ type: 'callPhone',
        showAlert: false,
        alertConfig: {
          title: '人职初需要拨打电话权限',
          btnTexts: ['取消', '去开启']
        } }).then(() => {
        resolve()
      })
    } else {
      resolve()
    }
  })
    .then(() => {
      return Linking.openURL(`tel:${phone}`)
    }).catch(() => {
      CommonToast('拨打电话失败')
    })
}
